package net.seehope.foodie.code;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.util.Random;

import net.seehope.foodie.properties.ProjectProperties;

/**
 * 这是一个条件装配逻辑，子模块在使用的时候，如果实现了ImageCodeGenerator接口，
 * 那么就使用子模块的实现，如果子模块没有实现，那么就用这个默认的逻辑，因此不能用@Component将其注入到容器中。
 * 一旦注入，表示写死了
 * 
 * 装配方式改变了
 * @author Administrator
 *
 */
public class DefaultImageGeneratorImpl implements ImageCodeGenerator{
	
	private ProjectProperties properties;

	@Override
	public ValidateCode generator() {
		
		return createCode();
	}
	
	/**
     * 可配置验证码生成参数
     * 可配置的验证码验证地址
     * 可配置的验证生成逻辑
     * 
     * @return
     */
    public ImaValidateCode createCode() {

        int width = properties.getCode().getWidth();
        int height = properties.getCode().getHeight();

        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);

        Graphics g = image.getGraphics();

        Random random = new Random();

        g.setColor(getRandColor(200, 250));
        g.fillRect(0, 0, width, height);
        g.setFont(new Font("Times New Roman", Font.ITALIC, 20));
        g.setColor(getRandColor(160, 200));
        for (int i = 0; i < 155; i++) {
            int x = random.nextInt(width);
            int y = random.nextInt(height);
            int xl = random.nextInt(12);
            int yl = random.nextInt(12);
            g.drawLine(x, y, x + xl, y + yl);
        }

        StringBuilder sRand = new StringBuilder();
        for (int i = 0; i < properties.getCode().getLength(); i++) {
            String rand = String.valueOf(random.nextInt(10));
            sRand.append(rand);
            g.setColor(new Color(20 + random.nextInt(110), 20 + random.nextInt(110), 20 + random.nextInt(110)));
            g.drawString(rand, 13 * i + 6, 16);
        }

        g.dispose();

        //图片，随机字符串，过期时间
        return new ImaValidateCode(image,sRand.toString(), properties.getCode().getExpireln());
    }

    /**
    * 生成随机背景条纹
    *
    * @param fc 前景色
    * @param bc 背景色
    * @return RGB颜色
    */
    public Color getRandColor(int fc, int bc) {
        Random random = new Random();
        if (fc > 255) {
            fc = 255;
        }
        if (bc > 255) {
            bc = 255;
        }
        int r = fc + random.nextInt(bc - fc);
        int g = fc + random.nextInt(bc - fc);
        int b = fc + random.nextInt(bc - fc);
        return new Color(r, g, b);
    }

	public ProjectProperties getProperties() {
		return properties;
	}

	public void setProperties(ProjectProperties properties) {
		this.properties = properties;
	}
    
    
    

}
